package com.tiance.integration.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2018/12/21
 *
 * Description：
 *
 * Modification History:
 *
 */
public class BaseAdvice {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 获取当前方法
     * @param pjp
     * @return
     * @throws Throwable
     */
    protected Method getCurrentMethod(ProceedingJoinPoint pjp) throws Throwable {
        Signature sig = pjp.getSignature();
        MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Object target = pjp.getTarget();
        Method currentMethod = target.getClass()
                .getMethod(msig.getName(), msig.getParameterTypes());
        return currentMethod;
    }

    /**
     * 获取当前注解
     * @param method
     * @param annotationClass
     * @return
     */
    protected Annotation getMethodAnnotation(Method method, Class annotationClass) {
        return method.getAnnotation(annotationClass);
    }

    /**
     * 获取注解参数
     * @param methodName
     * @param annotation
     * @return
     */
    protected Object quietGetFromAnnotation(String methodName, Annotation annotation) {
        if (annotation == null) {
            return null;
        }

        try {
            return annotation.annotationType().getDeclaredMethod(methodName).invoke(annotation);
        } catch (Exception e) {
            logger.debug(e.getMessage());
            // ignore
        }
        return null;
    }
}
